<?php
	$user = array('id' => intval($_REQUEST['users_id']));
	
	if (local_post()) {
		$errors = array();
		//check for duplicate username
		if (strlen($_POST['username']) < 5) $errors[] = 'Usernames must be at least 5 characters long.';
		else {
  		$sql = "SELECT COUNT(1) FROM users WHERE username = '{$_POST['username']}'";
  		if ($user['id'] != 0) $sql.= " AND id != '{$user['id']}'";
  		if (db_result(db_query($sql), 0) > 0) $errors[] = "That username is already in use.";
		}
			
		if (!empty($_POST['password'])) {
			if ($_POST['password'] != $_POST['password_confirm']) $errors[] = 'Passwords do not match.';
			elseif (strlen($_POST['password']) < 5) $errors[] = 'Passwords must be at least 5 characters long.';
		}
		
		if (!valid_email($_POST['email'])) $errors[] = 'Invalid email address!';
		
		if (!empty($errors)) errors($errors);
		else {
			$user['username'] = db_escape_string($_POST['username']);
			$user['first_name'] = db_escape_string($_POST['first_name']);
			$user['last_name'] = db_escape_string($_POST['last_name']);
			$user['phone'] = db_escape_string($_POST['phone']);
			$user['cell'] = db_escape_string($_POST['cell']);
			$user['fax'] = db_escape_string($_POST['fax']);
			$user['active'] = intval($_POST['active']);
			$user['images_id_default'] = intval($_POST['images_id_default']);
			
			$user = db_save($user, 'users');
			
			//save the password ** must be after first save so we have the username already
			if (!empty($_POST['password'])) {
				$user['password'] = $_POST['password'];
				$user = db_save($user, 'users');
			}
			
			
			if (authorized('users_to_user_roles', 'delete', true) && authorized('users_to_user_roles', 'insert', true)) { 
  			//save roles
  			db_query("DELETE FROM users_to_user_roles WHERE users_id = {$user['id']}");
  			foreach ($_POST['user_roles'] as $user_roles_id) {
  				db_query("INSERT INTO users_to_user_roles (users_id, user_roles_id) VALUES ({$user['id']}, $user_roles_id)");
  			}
			} else warning('You do not have permission to edit User Role membership.');
			
			
			
			
			
			
			
			
			##########################################################################
			##### IMAGES #############################################################
			##########################################################################
			
  		if($user['id'] != 0) {
     		$upload_errors =  array('UPLOAD_ERR_OK', 'UPLOAD_ERR_INI_SIZE', 'UPLOAD_ERR_FORM_SIZE', 'UPLOAD_ERR_PARTIAL', 'UPLOAD_ERR_NO_FILE', 'UPLOAD_ERR_NO_TMP_DIR', 'UPLOAD_ERR_CANT_WRITE', 'UPLOAD_ERR_EXTENSION');
      
      	if (!empty($_FILES['image']['error']) && $_FILES['image']['error'] != 4) error($upload_errors[$_FILES['image']['error']]);
  			elseif (authorized('images', 'insert', true)) {
        	if (is_uploaded_file($_FILES['image']['tmp_name'])) {						
          	$image = array();
          	$image['id'] = 0;
          	$image['record_table'] = 'users';
          	$image['record_id'] = $user['id'];
          	if ($image['purge'] != 1) unset($image['purge']);
    				
        		$image['original'] = file_get_contents($_FILES['image']['tmp_name']);
        		$image['mime'] = $_FILES['image']['type'];
        
        		$blob_360 = gd_img($image['original'], 360, 0, $image['mime']);
        		$image['width_360'] = $blob_360['image'];
        
        		$blob_720 = gd_img($image['original'], 720, 0, $image['mime']);
        		$image['width_720'] = $blob_720['image'];
        
        		$blob_1440 = gd_img($image['original'], 1440, 0, $image['mime']);
        		$image['width_1440'] = $blob_1440['image'];
        
        		$image['original'] = addslashes($image['original']);
        
        		$image = db_save($image, 'images');
						
            if($image['id'] != 0) success("Image uploaded Successfully!");
            else error("There was a problem uploading the image");
    				
    				$user = db_select($user['id'], 'users', false, true);
            if ($user['images_id_default'] == 0) $user['images_id_default'] = $image['id'];
        	}	
        } else warning('You do not have permission to add new images.');
    	}
			
			if (authorized('images', 'update', true)) {    		
        if(is_array($_POST['images'])) {
        	foreach($_POST['images'] as $id => $images_change) {
          	$images_change['id'] = $id;
            if($images_change['purge'] == 1) {
  						$sql = "DELETE FROM images WHERE id = $id";
  						echo $sql;
  						db_query($sql) or die(db_error());
            } else {
  						unset($images_change['purge']);
            
              $saved = db_save($images_change, 'images');
              if(empty($saved['id'])) error("There was an error changing an image.");
  					}
          }
        }
			}
			
  		//save primary image...
  		$user = db_save($user, "users");
			
  		//handle image cropping
  		$user = db_select($user['id'], 'users');
  		if ($user['images_id_default'] != 0 && (!empty($_POST['cropped_image_x']) || !empty($_POST['cropped_image_y']) || !empty($_POST['cropped_image_w']) || !empty($_POST['cropped_image_h']))) {
    		if (authorized('images', 'update', true)) { 	
					$sql = "SELECT id, width_360 FROM images WHERE id = {$user['images_id_default']}";
    			$qry = db_query($sql);
    			$image = mysql_fetch_assoc($qry);
    			
        	$targ_w = JCROP_WIDTH;
    			$targ_h = JCROP_HEIGHT;
        	$jpeg_quality = JCROP_QUALITY;
    			
        	$img_r = imagecreatefromstring($image['width_360']);
    			
    			unset($image['width_360']);
    			
        	$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
        
        	imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['cropped_image_x'], $_POST['cropped_image_y'], $targ_w, $targ_h, $_POST['cropped_image_w'], $_POST['cropped_image_h']);
        	
    			ob_start();
        	imagejpeg($dst_r, null, $jpeg_quality);
    			$image_data = ob_get_contents();
    			$image_data_length = ob_get_length();
    			ob_end_clean();
    			$image['cropped'] = addslashes($image_data);  			
    			db_save($image, 'images');
    		} else warning('You do not have permission to crop images.');
			}
			
			##########################################################################
			##### eof / images #######################################################
			##########################################################################
			
			
			
			
			
			
			
			
			//alwayse force admin account uid=-1 to be in super admin group gid=-1
			if ($user['id'] == -1) db_query("REPLACE INTO users_to_user_roles (users_id, user_roles_id) VALUES (-1, -1)");
			
			if ($_POST['button'] == 'Save and Close') location('/users/admin/index');
			elseif ($_POST['button'] == 'Save and New') location('/users/admin/edit');
		}
	}
	
	$user = db_select($user['id'], 'users');
?>

<form action="?users_id=<?php echo $user['id']?>" method="post" enctype="multipart/form-data">
	<fieldset>
		<legend>Login Credentials</legend>
		
		<label for="username">
			Username
			<input type="text" name="username" id="username" value="<?php echo $user['username']?>" />
		</label>
		
		<label for="password">
			Password
			<input type="password" name="password" id="password" value="" />
		</label>
		
		<label for="password_confirm">
			Confirm Password
			<input type="password" name="password_confirm" id="password_confirm" value="" />
		</label>
		
		<label for="active">
			<input type="checkbox" name="active" id="acitve" value="1" <?php if ($user['active'] == 1) echo 'checked="checked" '; ?>/>
			Active
		</label>
	</fieldset>
	
	<fieldset>
		<legend>Name</legend>
		
		<label for="first_name">
			First Name
			<input type="text" name="first_name" id="first_name" value="<?php echo $user['first_name']?>" />
		</label>
		
		<label for="last_name">
			Last Name
			<input type="text" name="last_name" id="last_name" value="<?php echo $user['last_name']?>" />
		</label>
	</fieldset>
	
	<fieldset>
		<legend>Contact Information</legend>
		
		<label for="email">
			Email
			<input type="text" name="email" id="email" value="<?php echo $user['email']?>" />
		</label>
		
		<label for="phone">
			Phone
			<input type="text" name="phone" id="phone" value="<?php echo $user['phone']?>" />
		</label>
		
		<label for="cell">
			Cell
			<input type="text" name="cell" id="cell" value="<?php echo $user['cell']?>" />
		</label>
		
		<label for="fax">
			Fax
			<input type="text" name="fax" id="fax" value="<?php echo $user['fax']?>" />
		</label>
	</fieldset>
	
	<fieldset>
		<legend>Roles</legend>
		
		<ul>
  	<?php
  		$sql = "SELECT id, name FROM user_roles ORDER BY name ASC";
			$qry = db_query($sql);
			while ($user_role = db_fetch_assoc($qry)) {
				if ($user_role['id'] == -1 && $user['id'] == -1) $checked = 'checked="checked" disabled="disabled" ';
				else $checked = (db_table_to_table($user['id'], $user_role['id'], 'users_to_user_roles')) ? 'checked="checked" ' : '';
		?>
			<li>
				<label for="role_<?php echo $user_role['id']?>">
					<input type="checkbox" name="user_roles[]" id="role_<?php echo $user_role['id']?>" value="<?php echo $user_role['id']?>" <?php echo $checked?>/>
					<?php echo $user_role['name']?>
				</label>
			</li>
		<?php
			}
  	?>
		</ul>
	</fieldset>
	
	
	<fieldset style="clear:both;" id="images">
  	<legend>Image(s)</legend>
    <span class="file">
      Upload Image&hellip;
      <input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
      <input type="file" name="image" />
      <input type="submit" value="Upload" />
  	</span>
    <?
			$sql = "SELECT * FROM images WHERE record_table = 'users' AND record_id = '{$user['id']}' AND record_id != '0' ORDER BY sort, id ASC";
			$qry = db_query($sql);
			while ($image = db_fetch_assoc($qry)) {
		?>
    <div style="clear:both;">
  		<span>
      	<img src="<?php echo PHPDRIVER_WEB?>images/index.php?images_id=<?=$image['id']?>&amp;width=60" alt="<?=$image['id']?>"  />
      </span>
    	<span>
   			Sort Key
  			<input type="text" name="images[<?=$image['id']?>][sort]" value="<?=$image['sort']?>" style="width: 50px;" />
  		</span>
      <span class="radial">
  	    Primary&nbsp;Image
  			<span>
        	<input type="radio" name="images_id_default" value="<?=$image['id']?>" <? if ($image['id'] == $user['images_id_default']) echo 'checked="checked" '; ?>/>
        </span>
      </span>
      <span class="radial">
      	Delete
        <span>
      		<input type="checkbox" name="images[<?=$image['id']?>][purge]" value="1" />
        </span>
      </span>
    </div>
		<?
			}
		?>
  </fieldset>
	
	<fieldset>
		<legend>Generate a Thumbnail by Cropping</legend>
		
	<?
		if ($user['images_id_default'] != 0) {
	?>
		<script src="<?php echo PHPDRIVER_WEB?>plugins/jcrop/js/jquery.Jcrop.js"></script>
		<link rel="stylesheet" href="<?php echo PHPDRIVER_WEB?>plugins/jcrop/css/jquery.Jcrop.css" type="text/css" />
		<link rel="stylesheet" href="<?php echo PHPDRIVER_WEB?>plugins/jcrop/demos/demo_files/demos.css" type="text/css" />
		<script language="Javascript">

			$(function(){

				$('#cropbox').Jcrop({
					aspectRatio: <?php echo JCROP_ASPECT_RATIO?>,
					bgColor:     '<?php echo JCROP_BGCOLOR?>',
					bgOpacity:   <?php echo JCROP_BGOPACITY?>,
					onSelect: updateCoords
				});

			});

			function updateCoords(c)
			{
				$('#x').val(c.x);
				$('#y').val(c.y);
				$('#w').val(c.w);
				$('#h').val(c.h);
			};

		</script>
		
		<img src="<?php echo PHPDRIVER_WEB?>images/index.php?images_id=<?=$user['images_id_default']?>&amp;width=<?php echo JCROP_WIDTH?>&amp;cropped" width="<?php echo JCROP_WIDTH?>" height="<?php echo JCROP_HEIGHT?>" align="right" border="2" />
		
		<img src="<?php echo PHPDRIVER_WEB?>images/index.php?images_id=<?=$user['images_id_default']?>&amp;width=360" id="cropbox" />

		<br />
  	<input type="hidden" id="x" name="cropped_image_x" />
  	<input type="hidden" id="y" name="cropped_image_y" />
  	<input type="hidden" id="w" name="cropped_image_w" />
  	<input type="hidden" id="h" name="cropped_image_h" />
  	<input type="submit" value="Crop Image" />
	<?
		} else echo 'Please select a &quot;Primary Image&quot;';
	?>
	</fieldset>
	
	<?php save_buttons(); ?>
</form>